import 'package:cached_network_image/cached_network_image.dart';
import 'package:cher_flare/config/url_api.dart';
import 'package:cher_flare/http/http_utils.dart';
import 'package:cher_flare/utils/ly_use_log_manager.dart';
import 'package:cher_flare/utils/size_fit.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:images_picker/images_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_manager/photo_manager.dart';

import '../../common/models/ly_image_model.dart';
import '../../common/models/ly_oss_policy_model.dart';
import '../../modules/login/models/ly_login_info_manager.dart';
import '../../modules/login/models/ly_login_model.dart';
import '../../utils/app_color.dart';
import 'package:intl/intl.dart';
import 'package:dio/dio.dart' as dio;

class LYPersonalInfoEditPage extends StatefulWidget {
  const LYPersonalInfoEditPage({super.key});

  @override
  State<LYPersonalInfoEditPage> createState() => _LYPersonalInfoEditPageState();
}

class _LYPersonalInfoEditPageState extends State<LYPersonalInfoEditPage> {
  final nameController = TextEditingController();
  late DateTime birthday;
  String country = '';
  List countrys = [
    'USA',
    'Canada',
    'Mexico',
    'Greenland',
    'Finland',
    'Britain',
    'Holand',
    'France',
    'Monaco',
    'Bulgaria',
    'Serbia',
    'Albania'
  ];
  String? avatar;

  void _avatarDidClick() {
    showModalBottomSheet(
      context: context,
      builder: (ctx) {
        return CupertinoActionSheet(
          actions: [
            InkWell(
              onTap: () {
                Navigator.of(context).pop();
                _takePhoto();
              },
              child: Container(
                height: 50,
                alignment: Alignment.center,
                child: const Text('Camera'),
              ),
            ),
            InkWell(
              onTap: () {
                Navigator.of(context).pop();
                _pickerImage();
              },
              child: Container(
                height: 50,
                alignment: Alignment.center,
                child: const Text('Photo Album'),
              ),
            ),
            InkWell(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Container(
                height: 50,
                alignment: Alignment.center,
                child: const Text('Cancel'),
              ),
            ),
          ],
        );
      },
      backgroundColor: Colors.transparent,
    );
  }

  void _pickerImage() async {
    final status = await Permission.photos.request();
    if (status == PermissionStatus.denied) {
      EasyLoading.showToast('You have not authorised this permission.');
      return;
    }
    List<Media>? result = await ImagesPicker.pick(
      count: 1,
      pickType: PickType.image,
    );
    if (result != null) {
      _uploadImage(result.first);
    }
  }

  void _takePhoto() async {
    final status = await Permission.camera.request();
    if (status == PermissionStatus.denied) {
      EasyLoading.showToast('You have not authorised this permission.');
      return;
    }
    List<Media>? result = await ImagesPicker.openCamera();
    if (result != null) {
      _uploadImage(result.first);
    }
  }

  void _uploadImage(Media media) async {
    EasyLoading.show(maskType: EasyLoadingMaskType.black);
    final res = await HttpUtils.getInstance.get(URLApi.ossPolicy);
    final model = LyOssPolicyModel.fromJson(res.data);
    DateTime dateTime = DateTime.now();
    String fileName = media.path.split('/').last;
    String format = fileName.split('.').last;
    int imageTimeName = dateTime.millisecondsSinceEpoch +
        (dateTime.microsecondsSinceEpoch ~/ 1000000);
    String imageName = '$imageTimeName.$format';
    String host = model.host ?? '';
    String dir = model.dir ?? '';
    var filePath =
        await dio.MultipartFile.fromFile(media.path, filename: fileName);
    final formData = dio.FormData.fromMap({
      'ossaccessKeyId': model.accessKeyId,
      'policy': model.policy,
      'signature': model.signature,
      'callback': model.callback,
      'key': '$dir/$imageName',
      'file': filePath,
    });

    final response = await HttpUtils.getInstance.post(host, data: formData);
    if (response.isSuccess) {
      final filename = response.data['filename'] as String?;
      final updateResponse = await HttpUtils.getInstance
          .post(URLApi.updateAvatar, data: {'avatarPath': filename});
      final imageModel = LyImageModel.fromJson(updateResponse.data);
      LYLoginInfoManager.getInstance.updateAvatarInfo(imageModel);
      avatar = imageModel.thumbUrl;
      setState(() {});
    }
    EasyLoading.dismiss();
  }

  void _submitButtonDidClick() async {
    if (nameController.text.isEmpty) {
      return;
    }
    if (country.isEmpty) {
      return;
    }
    EasyLoading.show(maskType: EasyLoadingMaskType.black);
    Map<String, dynamic> parameters = {
      'nickname': nameController.text,
      'country': country,
      'birthday': DateFormat('yyyy-MM-dd').format(birthday),
    };
    final res =
        await HttpUtils.getInstance.post(URLApi.saveUserInfo, data: parameters);
    EasyLoading.dismiss();
    if (res.isSuccess) {
      _getUserInfo();
    }
  }

  void _getUserInfo() async {
    final userInfo = LYLoginInfoManager.getInstance.loginModel?.userInfo;
    EasyLoading.show();
    final res = await HttpUtils.getInstance.get(URLApi.getUserInfo,
        queryParameters: {'userId': userInfo?.userId ?? ''});
    if (res.isSuccess) {
      final userModel = UserInfo.fromJson(res.data);
      LYLoginInfoManager.getInstance.updateUserInfo(userModel);
      Get.close(0);
    }
    EasyLoading.dismiss();
  }

  void _birthdayDidClick() {
    final picker = Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          margin: EdgeInsets.only(left: 30, right: 30),
          height: 300,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
          ),
          clipBehavior: Clip.hardEdge,
          child: CupertinoDatePicker(
            onDateTimeChanged: (date) {
              setState(() {
                birthday = date;
              });
            },
            mode: CupertinoDatePickerMode.date,
            dateOrder: DatePickerDateOrder.dmy,
            maximumYear: DateTime.now().year - 18,
            initialDateTime: birthday,
            backgroundColor: AppColors.whiteColor,
          ),
        ),
      ],
    );
    Get.dialog(picker, useSafeArea: false);
  }

  void _countryDidClick() {
    final index = countrys.indexOf(country);
    final countryController = FixedExtentScrollController(initialItem: index);
    final picker = Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          margin: const EdgeInsets.only(left: 30, right: 30),
          height: 300,
          width: 300,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
          ),
          clipBehavior: Clip.hardEdge,
          child: CupertinoPicker.builder(
            backgroundColor: AppColors.whiteColor,
            scrollController: countryController,
            itemExtent: 50,
            onSelectedItemChanged: (index) {
              country = countrys[index];
              setState(() {});
            },
            itemBuilder: (ctx, index) {
              final title = countrys[index];
              return Container(
                alignment: Alignment.center,
                child: Text(
                  title,
                  style: const TextStyle(fontSize: 15, color: Colors.black),
                ),
              );
            },
            childCount: countrys.length,
          ),
        ),
      ],
    );
    Get.dialog(picker, useSafeArea: false);
  }

  @override
  void initState() {
    super.initState();
    final userInfo = LYLoginInfoManager.getInstance.loginModel?.userInfo;
    nameController.text = userInfo?.nickname ?? '';
    birthday = DateTime.tryParse(userInfo?.birthday ?? '') ??
        DateTime(
            DateTime.now().year - 18, DateTime.now().month, DateTime.now().day);
    country = userInfo?.country ?? '';
    avatar = userInfo?.avatarThumbUrl;
    LYUseLogManager.stat(page: LYLogPages.editAvatar);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Record',
          style: TextStyle(fontSize: 18, color: AppColors.color202020),
        ),
        backgroundColor: AppColors.colorD7FFDF,
        leading: InkWell(
          child: Image.asset(
            'assets/images/back_icon.png',
            width: 24,
            height: 24,
          ),
          onTap: () {
            Get.close(0);
          },
        ),
        elevation: 0,
        centerTitle: true,
      ),
      backgroundColor: AppColors.colorF3F8F6,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            margin: const EdgeInsets.only(top: 68, bottom: 32),
            alignment: Alignment.center,
            height: 100.px,
            child: Stack(
              alignment: Alignment.center,
              children: [
                Positioned(
                    child: ClipRRect(
                  borderRadius: BorderRadius.circular(50.px),
                  child: InkWell(
                    onTap: () => _avatarDidClick(),
                    child: CachedNetworkImage(
                      imageUrl: avatar ?? '',
                      width: 100.px,
                      height: 100.px,
                      fit: BoxFit.cover,
                    ),
                  ),
                )),
                Positioned(
                    left: 75.px,
                    top: 75.px,
                    child: Image.asset(
                      'assets/images/personal_camera_icon.png',
                      width: 26,
                      height: 26,
                    )),
              ],
            ),
          ),
          Container(
            height: 44.px,
            padding: const EdgeInsets.only(left: 20, right: 20),
            margin: const EdgeInsets.only(left: 32, right: 32, bottom: 24),
            decoration: BoxDecoration(
                color: AppColors.whiteColor,
                borderRadius: BorderRadius.circular(10)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  'Nick Name',
                  style: TextStyle(
                      color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.3),
                      fontSize: 12),
                ),
                Expanded(
                  child: TextField(
                    controller: nameController,
                    decoration: const InputDecoration(
                      hintText: 'Please input',
                      border: InputBorder.none,
                      enabledBorder: InputBorder.none,
                      focusedBorder: InputBorder.none,
                    ),
                    textAlign: TextAlign.end,
                    style: const TextStyle(
                        color: AppColors.color404040, fontSize: 16),
                  ),
                ),
              ],
            ),
          ),
          InkWell(
            onTap: () => _birthdayDidClick(),
            child: Container(
              height: 44.px,
              padding: const EdgeInsets.only(left: 20, right: 20),
              margin: const EdgeInsets.only(left: 32, right: 32, bottom: 24),
              decoration: BoxDecoration(
                  color: AppColors.whiteColor,
                  borderRadius: BorderRadius.circular(10)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    'Date of Birth',
                    style: TextStyle(
                        color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.3),
                        fontSize: 12),
                  ),
                  Text(
                    DateFormat('yyyy-MM-dd').format(birthday),
                    style: const TextStyle(
                        color: AppColors.color404040, fontSize: 16),
                  ),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () => _countryDidClick(),
            child: Container(
              height: 44.px,
              padding: const EdgeInsets.only(left: 20, right: 20),
              margin: const EdgeInsets.only(left: 32, right: 32, bottom: 24),
              decoration: BoxDecoration(
                  color: AppColors.whiteColor,
                  borderRadius: BorderRadius.circular(10)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: Text(
                      'Country',
                      style: TextStyle(
                          color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.3),
                          fontSize: 12),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        country ?? '',
                        style: const TextStyle(
                            color: AppColors.color404040, fontSize: 16),
                      ),
                      const Icon(
                        Icons.keyboard_arrow_right,
                        weight: 12,
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: SizedBox(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  InkWell(
                    onTap: () => _submitButtonDidClick(),
                    child: Container(
                      height: 48.px,
                      alignment: Alignment.center,
                      margin: const EdgeInsets.only(
                          left: 32, right: 32, bottom: 50),
                      decoration: BoxDecoration(
                          gradient: const LinearGradient(colors: [
                            AppColors.colorCCFF78,
                            AppColors.color78FF85
                          ]),
                          borderRadius: BorderRadius.circular(24.px)),
                      child: const Text(
                        'Submit',
                        style: TextStyle(
                            color: AppColors.color404040,
                            fontSize: 16,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
